﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using tvdbInterface;
using System.Threading;

namespace XMM.Dialoges.WebData
{
    /// <summary>
    /// Interaktionslogik für TVDBSearch.xaml
    /// </summary>
    public partial class TVDBSearch : Window
    {
        ObservableCollection<SearchResult> _SearchResults = new ObservableCollection<SearchResult>();

        ObservableCollection<SearchResult> SearchResults
        {
            get
            {
                return _SearchResults;
            }
        }

        public string SearchPattern { get; set; }

        public tvdbInterface.SearchResult SelectedResult { get; set; }

        public Objects.Series SelectedShow { get; set; }

        private Mutex mutSearchTVDB;

        public TVDBSearch(string sSearchPattern)
        {
            InitializeComponent();

            mutSearchTVDB = new Mutex();
            SearchPattern = sSearchPattern;
            txtSearchPattern.Text = SearchPattern;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lblSelectedTitle.Content = String.Empty;
            txbOverview.Text = String.Empty;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            ParameterizedThreadStart tsOnlineSearch = new ParameterizedThreadStart(doSearch);
            Thread thOnlineSearch = new Thread(tsOnlineSearch);
            thOnlineSearch.Start(new object[] { new Objects.SearchPattern(txtSearchPattern.Text) });

            //doSearch();
        }

        private void doSearch(object Data)
        {
            if (mutSearchTVDB.WaitOne(1000))
            {
                object[] oaSearchPattern = (object[])Data;
                Objects.SearchPattern oSearchPattern = (Objects.SearchPattern)oaSearchPattern[0];
                Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Durchsuche TheTVDB.com", true });

                Settings oSettings = new Settings();
                //_SearchResults = new ObservableCollection<SearchResult>();
                Dispatcher.Invoke(new clearSearchResultsCallback(clearSearchResults));

                List<tvdbInterface.SearchResult> lResults = tvdbInterface.tvdbInterface.findSeriesByTitle(oSettings.LibraryDataStorage + @"\tvdb\cache\", oSearchPattern.SearchPatternString, "GER");
                if (lResults != null && lResults.Count > 0)
                {
                    foreach (tvdbInterface.SearchResult oResult in lResults)
                    {
                        //_SearchResults.Add(oResult);
                        Dispatcher.Invoke(new addSearchResultCallback(addSearchResult), new object[] { oResult });
                    }
                }

                Dispatcher.Invoke(new refreshResultsCallback(refreshResults));
                Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Bereit...", false });

                mutSearchTVDB.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("Es wird bereits eine Suche ausgeführt. Bitte warten Sie das Ergebnis der laufenden Suche ab!", "Suche läuft bereits", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void clearSearchResults()
        {
            _SearchResults = new ObservableCollection<SearchResult>();
        }

        private delegate void clearSearchResultsCallback();

        private void addSearchResult(tvdbInterface.SearchResult oResult)
        {
            _SearchResults.Add(oResult);
        }

        private delegate void addSearchResultCallback(tvdbInterface.SearchResult oResult);

        private void refreshResults()
        {
            lvResults.ItemsSource = SearchResults;
            lvResults.Items.Refresh();
        }

        private delegate void refreshResultsCallback();

        private void lvResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lvResults.SelectedIndex > -1)
            {
                SelectedResult = (tvdbInterface.SearchResult)lvResults.SelectedItem;
            }
            else
            {
                SelectedResult = null;
            }

            showDetails();
        }

        private void showDetails()
        {
            if (SelectedResult != null)
            {
                Settings oSettings = new Settings();
                TvdbLib.Data.TvdbSeries oSelectedShow = tvdbInterface.tvdbInterface.downloadShortShowInfo(oSettings.LibraryDataStorage + "tvdb\\cache\\", SelectedResult.TvdbID, "GER");
                oSelectedShow.SeriesBanners[0].LoadThumb();
                //string sBannerURL = oSettings.LibraryDataStorage + "tvdb\\cache\\" + oSelectedShow.Id + "\\" + oSelectedShow.BannerPath.Replace('/', '\\');
                string sBannerFileName = oSelectedShow.SeriesBanners[0].BannerPath.Split('\\')[oSelectedShow.SeriesBanners[0].BannerPath.Split('\\').Count() - 1];
                //sBannerFileName = sBannerFileName.Remove(0, 1);
                //sBannerFileName = "-" + sBannerFileName;
                sBannerFileName = "thumb_graphical_" + oSelectedShow.Id.ToString() + "-" + sBannerFileName.Split('-')[1];
                string sBannerURL = oSettings.LibraryDataStorage + "tvdb\\cache\\" + oSelectedShow.Id + "\\" + sBannerFileName;
                // Assign Values to Details-Controls.
                lblSelectedTitle.Content = SelectedResult.ShowTitle;
                txbOverview.Text = SelectedResult.Overview;

                // Load Banner-Image-Preview.
                if (sBannerURL != String.Empty && System.IO.File.Exists(sBannerURL))
                {
                    //string sFullURL = SelectedResult.
                    imgBanner.Source = new BitmapImage(new Uri(sBannerURL, UriKind.Absolute));
                    imgBanner.Stretch = Stretch.Uniform;
                }

                // Toggle Details-Controls' Visibility.
                lblSelectedTitle.Visibility = System.Windows.Visibility.Visible;
                txbOverview.Visibility = System.Windows.Visibility.Visible;
                btnApply.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                // Toggle Details-Controls' Visibility.
                lblSelectedTitle.Visibility = System.Windows.Visibility.Hidden;
                txbOverview.Visibility = System.Windows.Visibility.Hidden;
                btnApply.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void btnApply_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            Close();
        }

        public void setStatus(string sNewMessage, bool bEnableMarquee)
        {
            pbStatus.IsIndeterminate = bEnableMarquee;
            lblStatus.Content = sNewMessage;
        }

        public delegate void setStatusCallback(string sNewMessage, bool bEnableMarquee);

        
    }
}
